package com.yunche.yunchebusiness.ui.activity.evaluate

import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.orhanobut.logger.Logger
import com.yunche.yunchebusiness.R
import com.yunche.yunchebusiness.base.BaseActivity
import com.yunche.yunchebusiness.common.CommonDialog
import com.yunche.yunchebusiness.common.Constant
import com.yunche.yunchebusiness.entity.*
import com.yunche.yunchebusiness.getSameStr
import com.yunche.yunchebusiness.mvp.contract.EvaluateContract
import com.yunche.yunchebusiness.mvp.presenter.EvaluatePresenter
import com.yunche.yunchebusiness.ui.activity.brand.BrandActivity
import com.yunche.yunchebusiness.ui.view.optionView.OptionItemClickListener
import com.yunche.yunchebusiness.utils.CommonUtils
import com.yunche.yunchebusiness.utils.MyToast
import com.yunche.yunchebusiness.utils.ToastyUtils
import kotlinx.android.synthetic.main.activity_evaluate.*

@Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
class EvaluateActivity : BaseActivity(), OptionItemClickListener, EvaluateContract.View {
    private val mPresenter by lazy {
        EvaluatePresenter()
    }
    var colorId = 0
    var carInfoEntity: BrandInfoEntity? = null

    private var colors = arrayListOf<String>()
    var defaultColor = arrayListOf("红", "黄", "绿", "黑", "白", "紫", "其他")
    var areaEntity = listOf<AreaEntity>()
    private var provinceName = ""
    private var areaName = ""
    var evaluateInfo: EvaluateInfo? = null

    override fun setLayout(): Int = R.layout.activity_evaluate

    override fun initView() {
        mPresenter.attachView(this)
        ov_evaluate_brand.setOnOptionItemClickListener(this)
        ov_evaluate_city.setOnOptionItemClickListener(this)
        ov_evaluate_color.setOnOptionItemClickListener(this)
        ov_evaluate_plate_time.setOnOptionItemClickListener(this)
    }

    override fun getColorSuccess(colorEntity: ColorEntity) {
        colors.clear()
        if (colorEntity.styleColor.isEmpty()) {
            for (color in defaultColor) {
                colors.add(color)
            }
        } else {
            colorEntity.styleColor.forEach {
                colors.add(it)
            }
        }

        showColor(colorEntity)
    }

    private fun showColor(colorEntity: ColorEntity) {
        val pvOptions = OptionsPickerBuilder(mContext!!,
            OnOptionsSelectListener { options1, _, _, _ ->
                ov_evaluate_color.setContent(colors[options1])
            }
        ).setTitleText("选择颜色").build<String>()
        pvOptions.setPicker(colors)
        pvOptions.show()
    }


    override fun getAreaSuccess(areas: List<AreaEntity>) {
        areaEntity = areas
        showProvince(areaEntity)
    }

    override fun showLoading() {
        CommonDialog.showLoading(mContext!!, Constant.Loading)
    }

    override fun hideLoading() {
        CommonDialog.cancle()
    }

    override fun showError(msg: String) {
        ToastyUtils.showError(msg)
    }


    override fun onOptionItemClickListener(position: Int) {
        when (position) {
            1 -> {
                openActivityForResult(BrandActivity::class.java, null, Constant.SELECT_MODEL_RESULT_CODE)
            }
            2 -> {
                showTimeDialog()
            }
            3 -> {

            }
            4 -> {
                if (carInfoEntity == null) {
                    ToastyUtils.showError("请先选择品牌")
                } else {
                    mPresenter.getColor(carInfoEntity?.modelId!!)
                }
            }
            5 -> {
                if (areaEntity.isEmpty()) {
                    mPresenter.getArea()
                } else {
                    showProvince(areaEntity)
                }

            }
        }
    }


    private fun showProvince(areaEntity: List<AreaEntity>) {
        var province = ArrayList<String>()

        for (areaEntity in areaEntity) {
            province.add(areaEntity.areaName)
        }
        val pvOptions = OptionsPickerBuilder(mContext!!,
            OnOptionsSelectListener { options1, options2, options3, v ->
                provinceName = province[options1]
                var city = arrayListOf<String>()
                city.clear()

                if (areaEntity[options1].listBaseArea.size == 1) {
                    city.add(provinceName)
                    showCity(city)
                } else {
                    for (baseArea in areaEntity[options1].listBaseArea) {
                        city.add(baseArea.areaName)
                    }
                    showCity(city)
                }
            }
        ).setTitleText("选择省份").build<String>()
        pvOptions.setPicker(province)
        pvOptions.show()
    }

    private fun showCity(citys: List<String>) {
        val pvOptions = OptionsPickerBuilder(mContext!!,
            OnOptionsSelectListener { options1, _, _, _ ->
                areaName = citys[options1]
                ov_evaluate_city.setContent(areaName)
            }
        ).setTitleText("选择城市").build<String>()
        pvOptions.setPicker(citys)
        pvOptions.show()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

        Logger.t("EvaluateActivity:返回值：").d(resultCode)
        when (resultCode) {
            Constant.SELECT_MODEL_RESULT_CODE -> {
                carInfoEntity = data?.getSerializableExtra(Constant.BRAND_INFO_ENTITY) as BrandInfoEntity
                ov_evaluate_brand.setContent(carInfoEntity?.seriesName!! + carInfoEntity?.modelName!!)
            }
            Constant.REFRESH_DATA -> {
                setResult(Constant.REFRESH_DATA)
                finish()
            }
        }

        super.onActivityResult(requestCode, resultCode, data)
    }

    private fun showTimeDialog() {
        val pvTime = TimePickerBuilder(mContext, OnTimeSelectListener { date, v ->
            ov_evaluate_plate_time.setContent(CommonUtils.getTimeByData(date.time))
        }).build().show()
    }

    override fun initData() {
        var extras = intent.extras
        if (extras != null) {
            evaluateInfo = extras.getSerializable("evaluateInfo") as EvaluateInfo
            ov_evaluate_city.setContent(evaluateInfo!!.cityName)
            ov_evaluate_plate_time.setContent(evaluateInfo!!.buyCarDate)
            et_mileage.setText("${evaluateInfo!!.mileage.toFloat() / 10000}")
            var modelCode = extras.getString("modelCode")
            ov_evaluate_brand.setContent(evaluateInfo?.brandName + "-" + "-" + evaluateInfo?.seriesName + evaluateInfo?.modelName)


            if (carInfoEntity == null) {
                carInfoEntity = BrandInfoEntity()
                carInfoEntity!!.brandCode = evaluateInfo?.bandCode
                carInfoEntity!!.modelCode = evaluateInfo?.modelCode
                carInfoEntity!!.seriesCode = evaluateInfo?.seriesCode
                carInfoEntity!!.modelName = evaluateInfo?.modelName
                carInfoEntity!!.brandName = evaluateInfo?.brandName
                carInfoEntity!!.seriesIcon = evaluateInfo?.icon

            }
        }
    }


    override fun initEvent() {
        btn_evaluate.setOnClickListener {
            var seriesName = ov_evaluate_brand.getContent()
            var plateTime = ov_evaluate_plate_time.getContent()
            var city = ov_evaluate_city.getContent().replace("市", "")
            var milieage = et_mileage.text.toString()

            var id = -1
            if (evaluateInfo != null) {
                id = evaluateInfo?.id!!
            }


            if (seriesName == "请选择") {
                MyToast.makeTextToast(mContext!!, "请选择车型车系", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            if (plateTime == "请选择") {
                MyToast.makeTextToast(mContext!!, "请选择上牌时间", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (city == "请选择") {
                MyToast.makeTextToast(mContext!!, "请选择上牌城市", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (seriesName == "请选择") {
                MyToast.makeTextToast(mContext!!, "请选择车型车系", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            if (milieage.getSameStr(".") > 1 || milieage.startsWith(".") || milieage.isEmpty()) {
                MyToast.makeTextToast(mContext!!, "里程填写有误，请重新填写", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            if (milieage.contains(".")) {
                if (milieage.split(".")[1].length > 2) {
                    MyToast.makeTextToast(mContext!!, "里程填写有误，请不要超过2位小数", Toast.LENGTH_SHORT).show()
                    return@setOnClickListener
                }
            }

            var bundle = Bundle()
            var evaluateInfo = EvaluateInfo(
                carInfoEntity?.brandCode!!,
                plateTime,
                city,
                0f,
                milieage,
                0f,
                carInfoEntity?.modelCode!!,
                carInfoEntity?.seriesCode!!,
                carInfoEntity?.modelName!!,
                carInfoEntity?.brandName!!,
                id,
                carInfoEntity?.seriesName,
                carInfoEntity?.seriesIcon
            )

            bundle.putSerializable("evaluateInfo", evaluateInfo)
            openActivityForResult(EvaluateInfoActivity::class.java, bundle, 0)
        }
    }

    override fun getEvaluateSuccess(evaluateEntity: EvaluateEntity) {
    }

    override fun saveEvaluateSuccess() {
    }

}
